package flex.cc.nursing.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.common.utils.CommonUtils;
import flex.cc.nursing.dto.entity.NursingInterfaceLogEntity;
import flex.cc.nursing.service.NursingInterfaceLogService;
import flex.cc.single.dto.entity.VerifyTaskEntity;
import flex.cc.single.service.VerifyTaskService;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.store.util.AESSingleUtil;
import flex.cc.store.util.SdSignUtil;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;
import flex.cc.util.APIConfigUtil;

/**
 * 
 * @author WANGCONG
 * 2022年3月23日上午11:26:18
 * @desc 健康护理核销通知上游
 */
@Service
public class NursingVerifyService {
	
	private static final Logger logger = LoggerFactory.getLogger(NursingVerifyService.class);
	@Resource
    private APIConfigUtil apiConfigUtil;
	@Resource
	private DictCodeService dictCodeService;
	@Resource
	private NursingInterfaceLogService interfaceLogService;
	@Resource
	private VerifyTaskService taskService;
	
	/**
	 * 
	 * @author WANGCONG
	 * 2022年3月23日上午11:28:15
	 * @desc 核销通知
	 */
	@Async
	public Map<String, String> verify(String orderNo, StoreCouponEntity couponEntity) {
		logger.info("---健康护理核销通知上游开始---");
		Map<String, String> resultMap = new HashMap<>();
		resultMap.put("code", "00");
		resultMap.put("msg", "成功");
		String storeUserName = apiConfigUtil.getSYApiConfig("storeUserName");
		String storePassword = apiConfigUtil.getSYApiConfig("storePassword");
		String storeKey = apiConfigUtil.getSYApiConfig("storeKey");
		String storeProTypeCode = apiConfigUtil.getSYApiConfig("storeProTypeCode");
		String storeWriteOffUrl = apiConfigUtil.getSYApiConfig("storeWriteOffUrl");
		long hxTime = new Date().getTime();
		String serviceItemCode = couponEntity.getActivityId(); //服务类型id
		String password = "";
		String sign = "";
		String cardNo = "";
		String specificServiceItems = "健康护理服务";//服务项目名称
		Map<String, Object> codeParams = new HashMap<String, Object>();
		codeParams.put("code", serviceItemCode);
		codeParams.put("typeCode", "activityName");
		DictCodeEntity codeVo = dictCodeService.getOneByParams(codeParams);
		if(codeVo!=null){
			specificServiceItems = codeVo.getValue();
		}
		try {
			cardNo = couponEntity.getPackageCodeCF();
			password = AESSingleUtil.encrypt(storePassword, storeKey);
			StringBuilder sb = new StringBuilder("");
			sb.append(storeUserName).append(password)
			  .append(storeProTypeCode).append(serviceItemCode).append(cardNo)
			  .append("1").append(hxTime);
			sign = SdSignUtil.MD5(sb.toString());
		} catch (Exception e) {
			return resultMap;
		}
		Map<String, Object> body = new HashMap<String, Object>();
		body.put("username", storeUserName);
        body.put("password", password);
        body.put("proTypeCode", storeProTypeCode);
        body.put("cardNo", cardNo); //父卡券号
        body.put("hxStatus", "1");
        body.put("hxTime", hxTime);
        body.put("sign", sign);
        body.put("serviceItemCode", serviceItemCode);
        body.put("specificServiceItems", specificServiceItems);
        body.put("jsPrice", ""); //结算价
        //增加子卡券信息
        body.put("isChildCoupon", "1"); //是否为子卡券，1-是
        List<HashMap<String, Object>> childCardList = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> childCard = new HashMap<String, Object>();
        childCard.put("childCardNo", couponEntity.getCouponNum()); //子卡券号
        childCard.put("useCount", "1");
        childCard.put("orderId", couponEntity.getOrderId()); //订单号
        childCardList.add(childCard);
        body.put("childCardList", childCardList);
        String requestBody = CommonUtils.toJSONString(body);
        Date requestDate = new Date();
        String resultJson = CommonUtils.storePost(storeWriteOffUrl, requestBody);
        Date responseDate = new Date();
        String resultCode = "success";  //响应码code
        if (resultJson != null) {
        	try {
        		JSONObject json = JSONObject.parseObject(resultJson);
//        		String resultCode = (String)json.get("resultCode");
//        	    String resultDesc = (String)json.get("resultDesc");
//        		if(PublicUtil.isNotEmpty(resultCode) && "0000".equals(resultCode)){//成功
//        			saveInterfaceLog("0", requestDate, requestBody, responseDate, resultJson, orderNo, couponEntity);
//        		}else{
//        			resultCode = "error";
//        			saveInterfaceLog("1", requestDate, requestBody, responseDate, resultJson, orderNo, couponEntity);
//        		}
        		int code = Integer.valueOf(json.get("resultCode").toString());
        		if(HttpStatus.SC_OK == code){ //调用成功
        			JSONObject results = (JSONObject)json.get("result");
        			String status = results.get("status").toString();
        			if("success".equals(status)){
        				saveInterfaceLog("0", requestDate, requestBody, responseDate, resultJson, orderNo, couponEntity);
        			}else{
        				resultCode = "error";
        				saveInterfaceLog("1", requestDate, requestBody, responseDate, resultJson, orderNo, couponEntity);
        			}
        		}else{
        			resultCode = "error";
        		}
        		
			} catch (Exception e) {
				resultCode = "error";
				saveInterfaceLog("1", requestDate, requestBody, responseDate, "响应报文解析异常："+resultJson, orderNo, couponEntity);
			}
        }else{
        	resultCode = "error";
        	saveInterfaceLog("1", requestDate, requestBody, responseDate, "响应报文为空", orderNo, couponEntity);
        }
        
        //add W 2022年4月2日10:20:25 根据核销结果，操作t_store_verify_task，定时复推上游核销通知任务---start
        VerifyTaskEntity taskVo = new VerifyTaskEntity();
        if("success".equals(resultCode)){
        	taskVo.setCouponNum(couponEntity.getCouponNum());
        	taskVo.setStatus(0); //核销结果：0-成功、1-失败
        	taskVo.setUpdateTime(new Date());
        	taskService.update(taskVo);
        }else{
        	//核销失败，根据卡券码判断t_store_verify_task中是否已存在，若不存在，则插入
        	Map<String, Object> task_params = new HashMap<String, Object>();
        	task_params.put("couponNum", couponEntity.getCouponNum());
        	VerifyTaskEntity vo = taskService.getOneByParams(task_params);
        	if(PublicUtil.isEmpty(vo)){
        		taskVo.setCouponNum(couponEntity.getCouponNum());
        		taskVo.setWriteOffUrl(storeWriteOffUrl);
        		taskVo.setCardType("5");//1-服务包到店、2-服务包代驾、3-单项到店、4-单项代驾、5-健康护理
        		taskVo.setRequestBody(requestBody);
        		taskVo.setResponseBody(resultJson);
        		taskVo.setStatus(1); //核销结果：0-成功、1-失败
        		taskVo.setCreateTime(new Date());
        		taskService.insert(taskVo);
        	}
        }
        //add W 2022年4月2日10:20:25 根据核销结果，操作t_store_verify_task，定时复推上游核销通知任务---end
        
		logger.info("---健康护理核销通知上游结束---");
		return resultMap;
	}

	/**
	 * 
	 * @author WANGCONG
	 * 2022年3月24日上午9:47:57
	 * @desc 护理接口日志保存
	 */
	private void saveInterfaceLog(String status, Date requestDate, String requestBody, Date responseDate,
			String resultJson, String orderNo, StoreCouponEntity couponEntity) {
		NursingInterfaceLogEntity logEntity = new NursingInterfaceLogEntity();
		logEntity.setOrderNo(orderNo);
		logEntity.setStatus(status);
		logEntity.setOrderId(couponEntity.getCouponNum());
		logEntity.setInterfaceName("核销接口");
		logEntity.setRequestTime(requestDate);
		logEntity.setRequestBody(requestBody);
		logEntity.setResponseBody(resultJson);
		logEntity.setResponseTime(responseDate);
		logEntity.setCreateTime(new Date());
		interfaceLogService.insert(logEntity);
	}
	
}
